package com.cx.test.pdf;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class Pdf2Img {
	
	public static void main(String[] args) {
		String source = "c:/Users/yitus/Desktop/data structures and algorithm analysis in java.pdf";
		String target = "c:/Users/yitus/Desktop/test6.jpg";
		pdf2Img(source, target, 5);
		System.out.println("finish..");
	}

	
	public static void pdf2Img(String source, String target, int x) {
		try {
			RandomAccessFile randomAccessFile = new RandomAccessFile(new File(source), "r");
			FileChannel fileChannel = randomAccessFile.getChannel();
			ByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
			PDFFile pdfFile = new PDFFile(byteBuffer);
			PDFPage pdfPage = pdfFile.getPage(x);
			Rectangle rectangle = new Rectangle(0, 0, (int)pdfPage.getBBox().getWidth(), (int)pdfPage.getBBox().getHeight());
			Image image = pdfPage.getImage(rectangle.width, rectangle.height, rectangle, null, true, true);
			
			PDFPage pdfPage2 = pdfFile.getPage(x + 1);
			Rectangle rect2 = new Rectangle(0, 0, (int)pdfPage2.getBBox().getWidth(), (int)pdfPage.getBBox().getHeight());
			Image image2 = pdfPage2.getImage(rect2.width, rect2.height, rect2, null, true, true);
			
			
			BufferedImage bufferedImage = new BufferedImage(rectangle.width, rectangle.height + rect2.height, BufferedImage.TYPE_INT_RGB);
			bufferedImage.getGraphics().drawImage(image, 0, 0, rectangle.width, rectangle.height, null);
			bufferedImage.getGraphics().drawImage(image2, 0, rectangle.height, rect2.width, rect2.height, null);
			
			FileOutputStream fileOutputStream = new FileOutputStream(target);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
			encoder.encode(bufferedImage);
			fileOutputStream.close();
			randomAccessFile.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
